package com.aplink.generic.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.widget.ArrayAdapter;

import com.aplink.generic.pojo.GenericObject;
import com.aplink.generic.pojo.controlspec.ListviewSpec;

public class SelectionAdapter extends ArrayAdapter<String> {
    private String column;
    private ArrayList<GenericObject> mGenericObjects;
    private String mValueColumn;

    public SelectionAdapter(final Context context, final int resource,
            final ArrayList<GenericObject> genericObjects,
            final ListviewSpec listviewSpec) {
        super(context, resource);
        this.mGenericObjects = genericObjects;
        if (!this.mGenericObjects.isEmpty()) {
            this.column = this.mGenericObjects.get(0).getTableName() + "."
                    + listviewSpec.getDisplayProperty();
            this.mValueColumn = this.mGenericObjects.get(0).getTableName()
                    + "." + listviewSpec.getValueProp();
        }
    }

    @Override
    public int getCount() {
        return this.mGenericObjects.size();
    }

    public ArrayList<GenericObject> getGenericObjects() {
        return this.mGenericObjects;
    }

    @Override
    public String getItem(final int position) {
        if (this.mGenericObjects.isEmpty()) {
            return super.getItem(position);
        }
        final GenericObject genericObject = this.mGenericObjects.get(position);
        return genericObject.getValue(this.column);
    }

    public GenericObject getObject(final int position) {
        if (this.mGenericObjects.isEmpty()) {
            return null;
        }
        return this.mGenericObjects.get(position);
    }

    @Override
    public int getPosition(final String value) {
        for (final GenericObject genericObject : this.mGenericObjects) {
            if (genericObject.getValue(this.mValueColumn).equalsIgnoreCase(
                    value)) {
                return this.mGenericObjects.indexOf(genericObject);
            }
        }
        return -1;
    }

    public String getValue(final int position) {
        if (this.mGenericObjects.isEmpty()) {
            return null;
        }
        final GenericObject genericObject = this.mGenericObjects.get(position);
        return genericObject.getValue(this.mValueColumn);
    }

    public void setGenericObjects(final ArrayList<GenericObject> genericObjects) {
        this.mGenericObjects = genericObjects;
    }
}
